package com.yokead.common.base;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.jiangzeyin.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.Config;
import com.yokead.util.UrlDecode;
import org.springframework.http.HttpHeaders;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * Created by jiangzeyin on 2017/6/30.
 */
public abstract class DiggingBaseControl extends AdminBaseControl {

    protected static final String UAG = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36";


//    protected void convertUrl(Elements elements, String url, String attrName) {
//        elements.forEach(element -> {
//            String src = element.attr(attrName);
//            if (StringUtil.isEmpty(src))
//                return;
//            element.attr(attrName, convertUrl(src, url));
//        });
//    }

    protected String convertUrl(String src, String url) {
        if (src.startsWith("http")) {
            return src;
        }
        if (src.startsWith("//")) {
            src = (url.startsWith("http://") ? "http:" : "https:") + src;
            return src;
        }
        if (src.startsWith("/")) {
            String tempUrl = url;
            while (true) {
                int eIndex = tempUrl.lastIndexOf("/");
                int sIndex = tempUrl.indexOf("/");
                if (sIndex + 1 == eIndex) {
                    break;
                }
                tempUrl = tempUrl.substring(0, eIndex);
            }
            return StringUtil.clearPath(tempUrl + "/" + src);
        } else {
            int end = url.lastIndexOf("/");
            int start = url.indexOf("/");
            String tempUrl;
            if (start + 1 < end) {
                tempUrl = url.substring(0, end);
            } else {
                tempUrl = url + "/";
            }
            url = url.replace("://", "");
            end = url.lastIndexOf("/");
            start = url.indexOf("/");
            if (end == start) {
                if (src.startsWith("../")) {
                    src = src.substring(2);
                } else if (src.startsWith("./")) {
                    src = src.substring(1);
                }
            } else {
                if (src.startsWith("./")) {
                    src = src.substring(1);
                } else {
                    while (true) {
                        if (src.startsWith("../")) {
                            src = src.substring(2);
                            if (tempUrl.endsWith("/")) {
                                tempUrl = tempUrl.substring(0, tempUrl.length() - 1);
                            }
                            int end_index = tempUrl.lastIndexOf("/");
                            tempUrl = tempUrl.substring(0, end_index);
                        } else {
                            break;
                        }
                    }
                }
            }
            return StringUtil.clearPath(tempUrl + "/" + src);
        }
    }

    /**
     * 备份文件
     *
     * @param file
     */
    public static void backIndexHtml(File file) {
        int count = 5;
        while (count-- >= 0) {
            File in = count == 0 ? new File(file, "index.html") : new File(file, String.format("index_%s.html", count));
            if (!in.exists()) {
                continue;
            }
            File out = new File(file, String.format("index_%s.html", count + 1));
            try {
                FileCopyUtils.copy(in, out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取记录列表
     *
     * @param file
     * @return
     */
    public static File[] listLogs(File file) {
        File[] files = file.listFiles((dir, name) -> {
            String[] temps = StringUtil.stringToArray(name, "_");
            if (temps == null) {
                return false;
            }
            if (temps.length == 2) {
                if (!"index".equals(temps[0])) {
                    return false;
                }
                // temps[1].split(".");
                temps = StringUtil.stringToArray(temps[1], ".");
                if (temps.length != 2) {
                    return false;
                }
                int index = StringUtil.parseInt(temps[0]);
                return index >= 1 && index <= 5;
            }
            return false;
        });
        assert files != null;
        Arrays.sort(files, (o1, o2) -> {
            long t1 = o1.lastModified();
            long t2 = o2.lastModified();
            if (t1 > t2) {
                return -1;
            }
            return 1;
        });
        return files;
    }


    /**
     * 下载文件
     *
     * @param httpUrl  url
     * @param saveFile save
     * @return true 下载成功
     * @throws Exception e
     */
    public static boolean httpDownload(String httpUrl, String saveFile, boolean h404) throws Exception {
        StringBuilder urlStr = new StringBuilder();
        String strs[] = httpUrl.split("/");
        for (int i = 0; i < strs.length; i++) {
            String s = strs[i];
            String andStr = i < strs.length - 1 ? "/" : "";
            if (StringUtil.isChinese(s)) {
                urlStr.append(UrlDecode.getURLEncode(s)).append(andStr);
            } else {
                urlStr.append(s).append(andStr);
            }
        }
        httpUrl = urlStr.toString();
        httpUrl = httpUrl.replace(" ", "%20");

        HttpResponse response = HttpRequest.get(httpUrl).header(HttpHeaders.USER_AGENT, UAG).executeAsync();

        int code = response.getStatus();
        if (h404) {
            if (code == 404 || code == 403) {
                return false;
            }
        }
        if (code != 200) {
            throw new RuntimeException(httpUrl + "下载文件状态码：" + code);
        }
        return response.writeBody(FileUtil.file(saveFile), null) > 0;
    }

//    public static String getTrueName(String keyName) {
//        init tryCount = 1;
//        String tempName = keyName;
//        while (true) {
//            try {
//                boolean uF = urlExists(tempName);
//                if (!uF) {
//                    tempName = String.format("%s_%s", keyName, tryCount++);
//                } else
//                    break;
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }
//        return tempName;
//    }


//    private static boolean urlExists(String keyName, int tryCount) throws IOException {
//        try {
//            String url = String.format("%s/%s", getDoMain(), keyName);
//            URL hUrl = new URL(url);
//            HttpURLConnection conn = (HttpURLConnection) hUrl.openConnection();
//            return 404 == conn.getResponseCode();
//        } catch (ConnectException e) {
//            if (tryCount < 5)
//                return urlExists(keyName, ++tryCount);
//            throw e;
//        }
//    }



}
